package utn.bi.DAO.conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class AbstractConnection implements IConnection {
	
	/** Database's connection object. */
	protected Connection conn;
	
	protected String userDB;
	protected String passDB;
	protected String hostDB;
	protected String portDB;
	
	
	
	/**
	 * The url means the connectionString, which is composed for the driver + host. This can be different depends of the DBMS
	 * (MySQL-Oracle-SQLServer-etc..).
	 */
	protected String url;
	
	public boolean connect(){
		String connString;
		connString = getUrl();

		try
		{
			this.conn = DriverManager.getConnection(connString, this.userDB, this.passDB);
			System.out.println("Try to connect with string: " + connString);
			return true;
		}
		catch (SQLException e)
		{
			System.out.println("Error trying to connect! " + e.toString());
			System.out.println("Trying to connect a second time: ");
			try
			{
				this.conn = DriverManager.getConnection(connString);
				return true;
			}
			catch (SQLException ex)
			{
				System.out.println("Error trying to connect 2 times! " + e.toString());
				return false;
			}
		}
	}
	
	// TODO [Maxi] Desconectar !!!
	
	/**
	 * Executes a simple SQL query and return the resultset.
	 * 
	 * @param query
	 *            string with the query to execute.
	 * @return the resultset when there are result and the query was sucessfully executed otherwise null.
	 * */
	public ResultSet executeQuery(String query) throws SQLException {
		Statement stmt = null;
		ResultSet rs = null;

		if (query == null)
			return null;

		stmt = this.conn.createStatement();
		if (stmt.execute(query))
			rs = stmt.getResultSet();

		return rs;
	}
	
	public boolean connect(String hostDB, String portDB, String userDB, String passDB){
		return false;
	}

	public boolean disconnect(){
		return false;
	}
	
	protected abstract String getUrl();

	// Generic getters and setters. 
	
	public String getUserDB() {
		return userDB;
	}

	public void setUserDB(String userDB) {
		this.userDB = userDB;
	}

	public String getPassDB() {
		return passDB;
	}

	public void setPassDB(String passDB) {
		this.passDB = passDB;
	}

	public String getHostDB() {
		return hostDB;
	}

	public void setHostDB(String hostDB) {
		this.hostDB = hostDB;
	}

	public String getPortDB() {
		return portDB;
	}

	public void setPortDB(String portDB) {
		this.portDB = portDB;
	} 
	
	
}
